/**
 * UUID生成工具
 * 支持生成UUID v1、v4和v5版本
 */
export const  UUIDGenerator = {
    /**
     * 生成UUID v1 (基于时间的UUID)
     * @returns {string} 符合UUID v1标准的字符串
     */
    v1() {
      let d = new Date().getTime();
      const uuid = 'xxxxxxxx-xxxx-1xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        const r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
      });
      return uuid;
    },
  
    /**
     * 生成UUID v4 (随机UUID)
     * @returns {string} 符合UUID v4标准的字符串
     */
    v4() {
      return 'uuid-xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        // 使用更可靠的随机数生成方式
        const r = crypto.getRandomValues(new Uint8Array(1))[0] % 16;
        const v = c === 'x' ? r : (r & 0x3 | 0x8);
        // 确保输出两位十六进制字符，小写形式（UUID标准）
        return v.toString(16).padStart(1, '0');
      });
    },
  
    /**
     * 生成UUID v5 (基于名称的SHA-1哈希UUID)
     * @param {string} name 用于生成UUID的名称
     * @param {string} namespace 命名空间UUID
     * @returns {string} 符合UUID v5标准的字符串
     */
    v5(name, namespace) {
      // 检查命名空间是否有效
      if (!this.isValid(namespace)) {
        throw new Error('Invalid namespace UUID for v5 generation');
      }
  
      // 转换命名空间UUID为16字节的缓冲区
      const namespaceBytes = Uint8Array.from(
        namespace.replace(/-/g, ''),
        (c, i, arr) => parseInt(arr.slice(i * 2, i * 2 + 2).join(''), 16)
      ).buffer;
  
      // 编码名称
      const nameBytes = new TextEncoder().encode(name);
  
      // 连接命名空间和名称
      const buffer = new Uint8Array(namespaceBytes.byteLength + nameBytes.byteLength);
      buffer.set(new Uint8Array(namespaceBytes), 0);
      buffer.set(nameBytes, namespaceBytes.byteLength);
  
      // 计算SHA-1哈希并生成UUID
      return new Promise(async (resolve) => {
        const cryptoObj = window.crypto || window.msCrypto;
        const hash = await cryptoObj.subtle.digest('SHA-1', buffer);
        const hashArray = new Uint8Array(hash);
        
        // 取前16字节并设置版本和变体
        const uuidBytes = hashArray.slice(0, 16);
        uuidBytes[6] = (uuidBytes[6] & 0x0F) | 0x50; // 版本5
        uuidBytes[8] = (uuidBytes[8] & 0x3F) | 0x80; // RFC4122变体
        
        // 转换为UUID字符串格式
        const hex = Array.from(uuidBytes, b => b.toString(16).padStart(2, '0')).join('');
        const uuid = [
          hex.substring(0, 8),
          hex.substring(8, 12),
          hex.substring(12, 16),
          hex.substring(16, 20),
          hex.substring(20, 32)
        ].join('-');
        
        resolve(uuid);
      });
    },
  
    /**
     * 验证UUID是否有效
     * @param {string} uuid 要验证的UUID字符串
     * @returns {boolean} 验证结果
     */
    isValid(uuid) {
      const regex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
      return regex.test(uuid);
    }
  };

  